/**
 * ================================ Kriac Translate V1 ================================
 *
 * => 中文 | 英文 | 西班牙语 | 日语 | 葡萄牙语 | 意大利语 | 德国 | 法国 | 韩文 | 俄罗斯
 *
 * => 使用方法: 修改 UUID 以及 Target 插件路径, 然后运行 yarn start
 *
 * ====================================================================================
 */

const UUID = "com.hotspot.streamdock.weather.sdPlugin";
const Target = `C:/Users/Administrator/AppData/Roaming/HotSpot/StreamDock/plugins/${UUID}`;

// 翻译参数
const path = require("path");
const fs = require("fs-extra");
const axios = require("axios");
const zh_CN = path.join(Target, "zh_CN.json");
if (!fs.pathExistsSync(zh_CN)) throw new Error("没有找到需要翻译的JSON文件");

const origin = require(zh_CN),
  translateArr = [],
  locals = {
    en: "english",
    pt: "portuguese",
    es: "spanish",
    it: "italian",
    fr: "french",
    de: "german",
    ja: "japanese",
    ko: "korean",
    ru: "russian",
    ar: "arabic",
  };

// 深度遍历
const deepForEach = (obj, callback) => {
  Object.entries(obj).forEach(([key, value]) => {
    if (typeof value === "object" && value !== null) {
      return deepForEach(value, callback);
    }
    obj[key] = callback(value);
  });
};
deepForEach(origin, (item) => translateArr.push(item));

// 翻译方法
// const API = "https://api.translate.zvo.cn";
const API = "https://america.api.translate.zvo.cn/translate.json";
const translateStrings = (arr, to) => {
  return axios.post(
    API,
    { to, from: "chinese_simplified", text: JSON.stringify(arr) },
    { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
  );
};

// 写入文件
Object.keys(locals).forEach(async (item) => {
  const res = await translateStrings(translateArr, locals[item]);
  deepForEach(origin, () => res.data.text.shift());
  fs.writeJSONSync(path.join(Target, `/${item}.json`), origin);
});
